package myJs.user.mission.plot

import myJs.Implicits._
import myJs.Utils._
import myJs.components.lefse.{CladogramLayoutComponent, LdaLayoutComponent}
import myJs.components.{FontArgComponent, FontFamilyComponent}

import scala.scalajs.js.Dynamic.{global => g}
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.myPkg.{LayerOptions, MiniColorsOptions}
import myJs.tool.Pojo._
import myJs.tool.Tool
import myJs.tool.Tool._
import myJs.user.FeatureSelectionTool
import myJs.user.workflowMission.featureSelectionResult.FeatureSelectionResult
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element, document}
import scalatags.Text.all._
import shared.Pojo.AllPlotData

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.{Date, UndefOr}

/**
 * Created by yz on 2019/4/25
 */
object CladogramTab {

  val curRPlot = Cladogram
  val tabId = curRPlot.name

  def init(idStr: String = "") = {
    refreshImage(idStr)
    refreshConfig(idStr)
    registerEvent
  }

  def refreshImage(idStr: String = "") = {
    val url = g.jsRoutes.controllers.MissionToolController.getWorkspaceImage().url.toString
    val fileName = "lefse_LDA.cladogram.png"
    val finalFileName = FeatureSelectionTool.getFinalFileName(idStr, fileName)
    $(s"#${tabId} img").attr("src",
      s"${url}?missionId=${Tool.getMissionId}&fileName=${finalFileName}&time=${new Date()}")
  }

  def myRun = {
    val idStr = FeatureSelectionResult.getIdStr
    val bv = $(s"#${tabId} #form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", messages("running"),
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(Tool.zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.MissionToolController.plot().url.toString
      val formData = $(s"#${tabId} #form").serialize()
      Ajax.post(url = s"${url}", data = s"${formData}&kind=${curRPlot.name}&idStr=${idStr}",
        headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        layer.close(index)
        val valid = rs("valid").toB
        if (valid) {
          refreshImage(idStr)
        } else {
          g.swal("Error", rs.myGet("message"), "error")
        }
      }
    }
  }

  def registerEvent = {
    $(document.body).offThenOn("click", s"#${tabId} .myRun", "", (y: Element) => {
      myRun
    })
  }

  def refreshLayoutArg(data: AllPlotData) = {
    val state = AllPlotDataTool.getCladogramLayoutState(data).copy(formJq = $(s"#${tabId} #form"))
    CladogramLayoutComponent.component(state)().renderIntoDOM(document.querySelector(s"#${tabId} #${tabId}Layout"))
  }

  def refreshFontArg(data: AllPlotData) = {
    val state = AllPlotDataTool.getState(data).copy(formJq = $(s"#${tabId} #form")).copy(
     claalphaShow = true, clapewShow = true, clascwShow = true, clapcwShow = true,
      mainTitleShow = true, mainTitleFontShow = true, clalfsShow=true,claclfsShow=true
    )
    FontArgComponent.component(state)().renderIntoDOM(document.querySelector(s"#${tabId} #myFontArg"))
  }


  def refreshConfig(idStr: String = "") = {
    bootStrapValidator
    getConfigData(curRPlot, idStr).map { data =>
      refreshLayoutArg(data)
      refreshFontArg(data)
    }
  }

  def bootStrapValidator = {
    val maxNumber = Double.MaxValue
    val fieldsMap = js.Dictionary(
      "clasc" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
          )
        )
      },
      "claml" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "clacs" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "clarsl" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "clalstartl" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "clalstopl" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "claastartl" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "claastopl" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "claminps" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "clamaxps" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "clarsp" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "claalpha" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "clapew" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "clascw" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "clapcw" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "clalfs" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
      "claclfs" -> {
        js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> s"${messages("null")}"
            ),
            "numeric" -> js.Dictionary(
              "message" -> s"${messages("numeric")}",
            ),
          )
        )
      },
    ).toMap
    val basicBVMap = (Tool.getPlotBootstrapValidator.toMap)
    val finalFields = (basicBVMap ++ fieldsMap).toJSDictionary
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> finalFields
    )
    $(s"#${tabId} #form").bootstrapValidator(dict)
  }

}
